package com.cm.goods.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cm.common.core.Result;
import com.cm.common.utils.COSStorage;
import com.cm.common.utils.StringUtil;
import com.cm.common.entity.Goods;
import com.cm.goods.entity.dto.GoodsKeyWordDTO;
import com.cm.goods.entity.vo.GoodsVO;
import com.cm.goods.mapper.GoodsMapper;
import com.cm.goods.service.GoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @类 名:GoodsController </br>
 * @描 述:<br>
 * @日 期:2020/9/23 22：31 </br>
 * @作 者:小兰同学</br>
 * @版 本：1.0.0
 * @since JDK 1.8
 *
 *
 *
 */
@RestController
@RequestMapping("/goods")
@Slf4j
public class GoodsController {
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    GoodsService goodsService;

    @PostMapping("/insert")
    public Result insert (@RequestBody Goods goods){
        System.out.println(goods);
        if (goodsService.insert(goods)) {
            return Result.success("商品添加成功");
        }
        return Result.fail(goods.getName() + "已存在！");
    }

    @PostMapping("/delete")
    public Result delete(Long id) {
        if (goodsService.delete(id)) {
            return Result.success("删除成功");
        }
        return Result.fail("删除失败");
    }

    @PostMapping("/update")
    public Result update(@RequestBody Goods goods) {
        if (goodsService.update(goods)) {
            return Result.success("修改成功");
        }
        return Result.fail("修改失败");
    }

    @PostMapping("/list")
    public Result getGoods(@RequestBody GoodsKeyWordDTO goodsKeyWordDTO) {
        IPage<GoodsVO> userIPage = goodsService.getGoodsList(goodsKeyWordDTO);
        return Result.success(userIPage);
    }

    @PostMapping("/getById")
    public Result getById(Long id){
        Goods goods=goodsMapper.selectById(id);
        return Result.success(goods);
    }
    @PostMapping("/setImage")
    public Result upload(MultipartFile file) throws IOException {
        String filename=file.getOriginalFilename();
        InputStream inputStream=file.getInputStream();
        COSStorage cosStorage = new COSStorage();
        String path = cosStorage.upload(inputStream, StringUtil.getFileExt(filename));
//        try {
//            cosFileStorage.fileUpload(file.getInputStream(), StringUtil.getFileExt(filename));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return Result.success(path);
    }
    @PostMapping("/getByType")
    public Result getByType(Long typeId){
        List<Goods> goodsList=goodsService.getGoodsByType(typeId);
        return Result.success(goodsList);
    }
}
